﻿#region Copyright

// All Material Copyright © 2010 Dynamic Concepts Development Corp., All Rights Reserved.
//      Portions Copyright © 1984-2009 Dynamic Concepts Development Corp., All Rights Reserved.
// For further information please contact: SoftwareSupport@dynconcepts.com
// Dynamic Concepts Development Corp.  311 W 57th St. Suite #422, New York, NY 10019

#endregion

#region Using References

using System;
using System.Collections.Generic;

#endregion

namespace DynConDevCorp.OpenArch.SupportLibrary.ParallelExecution
{
    public class TimingClock
    {
        #region Constructors

        public TimingClock()
        {
            Reset(false);
        }

        #endregion

        #region Public Properies and Indexers

        public TimeSpan Elapsed
        {
            get
            {
                DateTime endTime = m_IsPaused ? m_PauseStart : DateTime.UtcNow;
                TimeSpan totalTime = endTime - m_StartTime;
                TimeSpan elapsedTime = totalTime - m_PausedTime;
                return elapsedTime;
            }
        }

        #endregion

        #region Public Methods

        public void Pause()
        {
            if (!m_IsPaused)
            {
                m_IsPaused = true;
                m_PauseStart = DateTime.UtcNow;
            }
        }

        public void Reset(bool startRunning)
        {
            m_StartTime = DateTime.UtcNow;
            if (!startRunning)
            {
                m_IsPaused = true;
                m_PauseStart = m_StartTime;
            }
        }

        public void Resume()
        {
            if (m_IsPaused)
            {
                m_IsPaused = false;
                m_PausedTime = DateTime.UtcNow - m_PauseStart;
            }
        }

        #endregion

        #region Instance Fields (Mutable)

        private bool m_IsPaused;
        private DateTime m_PauseStart;
        private TimeSpan m_PausedTime;
        private DateTime m_StartTime;

        #endregion
    }

    public static class TimingClocks
    {
        #region Public Methods

        public static TimingClock Get(string name)
        {
            TimingClock retVal;
            if (!sr_TimingClocks.TryGetValue(name, out retVal))
            {
                retVal = new TimingClock();
                sr_TimingClocks.Add(name, retVal);
            }
            return retVal;
        }

        #endregion

        #region Static Fields and Constants

        private static readonly Dictionary<string, TimingClock> sr_TimingClocks = new Dictionary<string, TimingClock>();

        #endregion
    }
}